
import * as  crypto from 'crypto';

class Login {
    notCheck = ['/login'];
    users: {
        [key: string]: {
            userId: string,
            lastLogin: number;
        };
    } = {};

    /**
     * 查找存在->判断时间是否过期->未过期加时间
     * @param key 
     */
    isLogin(key: string) {
        let hasLogin = Reflect.has(this.users, key);
        if (!hasLogin) throw '未登录';

        let nowTime = new Date().getTime();
        let lastTime = this.users[key].lastLogin;
        if (nowTime - lastTime > 1000 * 60 * 30) {
            Reflect.deleteProperty(this.users, key);
            throw '登录信息过期,重新登录';
        } else {
            lastTime = nowTime;
        }
    }

    /**
     * 登录加密模块
     * @param userId 
     */
    crypto(userId: string) {
        let date = new Date();
        let md5 = crypto.createHash('md5');
        let result = md5.update(userId).digest("hex");

        let defineResult = Reflect.deleteProperty(this.users, result);
        if (!defineResult) '存储登录信息失败';
        Reflect.set(this.users, result, {
            userId,
            lastLogin: date.getTime()
        });

        return result;
    }

}

const loginUtil = new Login();
export default loginUtil;

